#!/bin/bash

# 设计模式学习平台 - 远程服务器部署脚本
# 用于将本地项目部署到远程1Panel服务器

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置变量 - 请根据您的服务器信息修改
SERVER_IP="110.42.208.140"
SERVER_USER="ubuntu"
SERVER_PORT="22"
REMOTE_PATH="/home/ubuntu/design-patterns"
PROJECT_NAME="design-patterns"

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 显示帮助信息
show_help() {
    echo "远程部署脚本使用说明："
    echo ""
    echo "用法: $0 <服务器IP> [选项]"
    echo ""
    echo "必需参数:"
    echo "  服务器IP              远程服务器的IP地址"
    echo ""
    echo "可选参数:"
    echo "  -u, --user USER       SSH用户名 (默认: root)"
    echo "  -p, --port PORT       SSH端口 (默认: 22)"
    echo "  --path PATH           远程部署路径 (默认: /home/ubuntu/design-patterns)"
    echo "  -h, --help            显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 192.168.1.100"
    echo "  $0 192.168.1.100 -u ubuntu -p 2022"
    echo "  $0 your-domain.com --path /home/ubuntu/my-design-patterns"
    echo ""
    echo "操作命令:"
    echo "  deploy   - 完整部署 (默认)"
    echo "  upload   - 仅上传文件"
    echo "  build    - 仅在远程构建"
    echo "  start    - 仅启动服务"
    echo "  stop     - 停止服务"
    echo "  logs     - 查看日志"
    echo "  status   - 查看状态"
}

# 解析命令行参数
parse_args() {
    if [[ $# -eq 0 ]] || [[ "$1" == "-h" ]] || [[ "$1" == "--help" ]]; then
        show_help
        exit 0
    fi
    
    SERVER_IP="$1"
    shift
    
    while [[ $# -gt 0 ]]; do
        case $1 in
            -u|--user)
                SERVER_USER="$2"
                shift 2
                ;;
            -p|--port)
                SERVER_PORT="$2"
                shift 2
                ;;
            --path)
                REMOTE_PATH="$2"
                shift 2
                ;;
            -h|--help)
                show_help
                exit 0
                ;;
            *)
                ACTION="$1"
                shift
                ;;
        esac
    done
    
    # 验证必需参数
    if [[ -z "$SERVER_IP" ]]; then
        log_error "请提供服务器IP地址"
        show_help
        exit 1
    fi
}

# 检查本地依赖
check_local_dependencies() {
    log_info "检查本地依赖..."
    
    # 检查SSH
    if ! command -v ssh &> /dev/null; then
        log_error "SSH 客户端未安装"
        exit 1
    fi
    
    # 检查SCP/RSYNC
    if command -v rsync &> /dev/null; then
        TRANSFER_CMD="rsync"
        log_info "使用 rsync 进行文件传输"
    elif command -v scp &> /dev/null; then
        TRANSFER_CMD="scp"
        log_info "使用 scp 进行文件传输"
    else
        log_error "未找到文件传输工具 (rsync 或 scp)"
        exit 1
    fi
    
    # 检查必要文件
    local required_files=("Dockerfile" "docker-compose.yml" "nginx.conf" "package.json")
    for file in "${required_files[@]}"; do
        if [[ ! -f "$file" ]]; then
            log_error "缺少必要文件: $file"
            exit 1
        fi
    done
    
    log_success "本地依赖检查通过"
}

# 测试SSH连接
test_ssh_connection() {
    log_info "测试SSH连接到 $SERVER_USER@$SERVER_IP:$SERVER_PORT ..."
    
    if ssh -o ConnectTimeout=10 -o BatchMode=yes -p "$SERVER_PORT" "$SERVER_USER@$SERVER_IP" "echo 'SSH连接成功'" &>/dev/null; then
        log_success "SSH连接正常"
    else
        log_error "SSH连接失败，请检查："
        echo "  1. 服务器IP地址是否正确"
        echo "  2. SSH端口是否正确"
        echo "  3. 用户名是否正确"
        echo "  4. SSH密钥是否已配置"
        echo "  5. 服务器防火墙是否开放SSH端口"
        exit 1
    fi
}

# 检查远程服务器环境
check_remote_environment() {
    log_info "检查远程服务器环境..."
    
    # 检查Docker
    if ! ssh -p "$SERVER_PORT" "$SERVER_USER@$SERVER_IP" "command -v docker" &>/dev/null; then
        log_error "远程服务器未安装 Docker"
        exit 1
    fi
    
    # 检查Docker Compose
    if ! ssh -p "$SERVER_PORT" "$SERVER_USER@$SERVER_IP" "command -v docker-compose" &>/dev/null; then
        log_error "远程服务器未安装 Docker Compose"
        exit 1
    fi
    
    # 检查1Panel (可选)
    if ssh -p "$SERVER_PORT" "$SERVER_USER@$SERVER_IP" "systemctl is-active 1panel" &>/dev/null; then
        log_success "1Panel 服务运行正常"
    else
        log_warning "未检测到1Panel服务，请确保1Panel已正确安装"
    fi
    
    log_success "远程环境检查通过"
}

# 上传项目文件
upload_files() {
    log_info "上传项目文件到远程服务器..."
    
    # 创建远程目录
    ssh -p "$SERVER_PORT" "$SERVER_USER@$SERVER_IP" "mkdir -p $REMOTE_PATH"
    
    # 排除不需要的文件和目录
    local exclude_list=(
        "--exclude=node_modules"
        "--exclude=dist"
        "--exclude=.git"
        "--exclude=logs"
        "--exclude=*.log"
        "--exclude=.DS_Store"
        "--exclude=.vscode"
        "--exclude=.idea"
    )
    
    if [[ "$TRANSFER_CMD" == "rsync" ]]; then
        # 使用rsync同步文件
        rsync -avz --progress \
            -e "ssh -p $SERVER_PORT" \
            "${exclude_list[@]}" \
            ./ "$SERVER_USER@$SERVER_IP:$REMOTE_PATH/"
    else
        # 使用scp上传文件
        log_info "创建临时压缩包..."
        tar -czf "/tmp/${PROJECT_NAME}.tar.gz" \
            --exclude='node_modules' \
            --exclude='dist' \
            --exclude='.git' \
            --exclude='logs' \
            --exclude='*.log' \
            ./
        
        scp -P "$SERVER_PORT" "/tmp/${PROJECT_NAME}.tar.gz" "$SERVER_USER@$SERVER_IP:/tmp/"
        
        ssh -p "$SERVER_PORT" "$SERVER_USER@$SERVER_IP" \
            "cd $REMOTE_PATH && tar -xzf /tmp/${PROJECT_NAME}.tar.gz --strip-components=1 && rm /tmp/${PROJECT_NAME}.tar.gz"
        
        rm "/tmp/${PROJECT_NAME}.tar.gz"
    fi
    
    log_success "文件上传完成"
}

# 远程构建
remote_build() {
    log_info "在远程服务器构建应用..."
    
    ssh -p "$SERVER_PORT" "$SERVER_USER@$SERVER_IP" "
        cd $REMOTE_PATH
        chmod +x deploy.sh
        
        # 尝试使用docker组权限，如果失败则使用sudo
        if groups | grep -q docker; then
            ./deploy.sh cleanup
            docker build -t design-patterns:latest .
        else
            sudo ./deploy.sh cleanup
            sudo docker build -t design-patterns:latest .
        fi
    "
    
    log_success "远程构建完成"
}

# 远程启动服务
remote_start() {
    log_info "在远程服务器启动服务..."
    
    ssh -p "$SERVER_PORT" "$SERVER_USER@$SERVER_IP" "
        cd $REMOTE_PATH
        
        # 尝试使用docker组权限，如果失败则使用sudo
        if groups | grep -q docker; then
            docker-compose up -d
        else
            sudo docker-compose up -d
        fi
    "
    
    log_success "服务启动完成"
}

# 检查部署状态
check_deployment_status() {
    log_info "检查部署状态..."
    
    # 检查容器状态
    if ssh -p "$SERVER_PORT" "$SERVER_USER@$SERVER_IP" \
        "cd $REMOTE_PATH && (docker-compose ps 2>/dev/null || sudo docker-compose ps) | grep -q 'Up'"; then
        log_success "容器运行正常"
    else
        log_error "容器运行异常"
        show_remote_logs
        exit 1
    fi
    
    # 检查健康状态
    log_info "等待健康检查..."
    for i in {1..30}; do
        if ssh -p "$SERVER_PORT" "$SERVER_USER@$SERVER_IP" \
            "curl -f http://localhost:8080/health" &>/dev/null; then
            log_success "应用健康检查通过"
            break
        fi
        if [ $i -eq 30 ]; then
            log_error "健康检查超时"
            exit 1
        fi
        sleep 2
    done
}

# 显示远程日志
show_remote_logs() {
    ssh -p "$SERVER_PORT" "$SERVER_USER@$SERVER_IP" \
        "cd $REMOTE_PATH && (docker-compose logs --tail=50 2>/dev/null || sudo docker-compose logs --tail=50)"
}

# 显示部署信息
show_deployment_info() {
    echo ""
    echo "=================================="
    log_success "远程部署完成！"
    echo "=================================="
    echo ""
    echo "服务器信息："
    echo "  服务器地址: $SERVER_IP"
    echo "  SSH用户: $SERVER_USER"
    echo "  SSH端口: $SERVER_PORT"
    echo "  部署路径: $REMOTE_PATH"
    echo ""
    echo "访问地址："
    echo "  HTTP: http://$SERVER_IP:8080"
    echo "  1Panel: 通过1Panel面板配置域名和SSL"
    echo ""
    echo "管理命令："
    echo "  查看状态: $0 $SERVER_IP status"
    echo "  查看日志: $0 $SERVER_IP logs"
    echo "  停止服务: $0 $SERVER_IP stop"
    echo "  重新部署: $0 $SERVER_IP deploy"
    echo ""
}

# 执行远程命令
execute_remote_action() {
    local action="$1"
    
    case "$action" in
        "upload")
            upload_files
            ;;
        "build")
            remote_build
            ;;
        "start")
            remote_start
            ;;
        "stop")
            ssh -p "$SERVER_PORT" "$SERVER_USER@$SERVER_IP" \
                "cd $REMOTE_PATH && (docker-compose down 2>/dev/null || sudo docker-compose down)"
            log_success "服务已停止"
            ;;
        "logs")
            show_remote_logs
            ;;
        "status")
            ssh -p "$SERVER_PORT" "$SERVER_USER@$SERVER_IP" \
                "cd $REMOTE_PATH && (docker-compose ps 2>/dev/null || sudo docker-compose ps)"
            ;;
        "deploy"|"")
            upload_files
            remote_build
            remote_start
            check_deployment_status
            show_deployment_info
            ;;
        *)
            log_error "未知操作: $action"
            show_help
            exit 1
            ;;
    esac
}

# 主函数
main() {
    echo "=================================="
    echo "  设计模式平台 - 远程部署脚本"
    echo "=================================="
    echo ""
    
    parse_args "$@"
    
    check_local_dependencies
    test_ssh_connection
    check_remote_environment
    
    execute_remote_action "${ACTION:-deploy}"
}

# 处理中断信号
trap 'log_error "部署过程被中断"; exit 1' INT TERM

# 运行主函数
main "$@"
